package com.bridgeintelligent.tag.webserver.dim.query.service;

import feign.Feign;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * Created by JackCheung on 2019/10/21 5:50 PM.
 */
@Component
public class QueryApiUtils {

    private Feign.Builder builder;
    private String url;
    private QueryUrlConfig queryConfig;

    public QueryApiUtils(QueryUrlConfig queryConfig) {
        this.queryConfig = queryConfig;
    }

    private synchronized void doInit(String url) {
        if (null == builder) {
            this.url = url;
            builder = Feign
                    .builder()
                    .decoder(createDecoder())
                    .encoder(createEncoder());
        }
    }

    private Decoder createDecoder() {
        return new JacksonDecoder();
    }

    private Encoder createEncoder() {
        return new JacksonEncoder();
    }

    private void init(String url) {
        if (StringUtils.isEmpty(url)) {
            url = queryConfig.getRequestUrl();
        }
        if (null != builder) {
            return;
        }
        doInit(url);
    }

    public <T> T build(Class<T> clazz) {
        init(url);
        return builder.target(clazz, url);
    }
}
